package rrrmai.repository;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Singleton;

import io.reactivex.Flowable;
import rrrmai.room.database.AppDataBase;
import rrrmai.service.APIService;
import rrrmai.service.PostService;
import rrrmai.viewbinder.Contact;
import rrrmai.viewbinder.Post;

/**
 * Created by az on 2018/3/20.
 */

@Singleton
public class ContactRepository extends Repository{
    //cache
    APIService mAPIService;
    AppDataBase mAppDataBase;

    @Inject
    public ContactRepository(APIService mAPIService, AppDataBase mAppDataBase){
            this.mAPIService=mAPIService;
            this.mAppDataBase=mAppDataBase;
    }

    public Flowable<List<Contact>> getContactList(int page, int pageSize) {
        dataSource(page,pageSize);
        Flowable db= mAppDataBase.contactDao().loadAll();
        Flowable api= mAPIService.getService(PostService.class)
                .getPostList(page,pageSize)
                .flatMap(listRsp -> Flowable.just(listRsp.getData()));
      return Flowable.merge(db,api);
    }

    public Long[] insert(List<Contact>  contacts) {
        return mAppDataBase.contactDao().insert(contacts);
    }

    public Long[] insert(Contact ... contact) {
          return mAppDataBase.contactDao().insert(contact);
    }

    public int delete(Contact ... contact) {
        return mAppDataBase.contactDao().delete(contact);
    }

    public int update(Contact ... contact) {
        return mAppDataBase.contactDao().update(contact);
    }

    private void dataSource(int page, int pageSize){

        /*mAPIService.getService(PostService.class)
                .getPostList(page,pageSize)
                .subscribe(new Consumer<Rsp<List<Post>>>() {
                    @Override
                    public void accept(Rsp<List<Post>> rsp) throws Exception {
                      //Long[] rowIds=  mAppDataBase.postDao().insertPostList(rsp.getData());
                        //Log.e("111",rowIds+"");
                    }
                });*/
    }

}
